package com.song.service.menu;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.song.common.Result;
import com.song.dao.menu.MenuDao;
import com.song.dao.menu.RoleMenuDao;
import com.song.entity.menu.Menu;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.song.entity.role.Role;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuDao,Menu> implements MenuService {

    @Autowired
    private MenuDao menuDao;

    @Autowired
    private RoleMenuDao roleMenuDao;

    @Override
    public Result<List<Menu>> selectMenuList(Menu menu, String startTime, String endTime, int pageNum, int pageSize) {
        Result<List<Menu>> result = new Result<>();
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = new HashMap<>();
        map.put("roleName",menu.getMenuName());
        map.put("startTime",startTime);
        map.put("endTime",endTime);
        map.put("status",menu.getStatus());

        List<Menu> roleList = menuDao.selectMenuList(map);
        PageInfo<Menu> pageInfo = new PageInfo<>(roleList);
        result.setCode(0);
        result.setCount((int)pageInfo.getTotal());
        result.setData(roleList);
        return result;
    }

    /**
     * 根据角色id,获得菜单树列表
     */
    @Override
    public JSONArray getMenuTreeByRoleId(Integer roleId) {
        // 所有菜单列表
        EntityWrapper ew = new EntityWrapper();
        ew.where("status={0}",0);
        ew.orderBy("menu_id");
        List<Menu> menus = menuDao.selectList(ew);
        // 角色所有的菜单权限
        List<Integer> menuIds = roleMenuDao.selectMenusByRoleId(roleId);
        return getMenus(menus,menuIds);
    }

    /**
     * 角色树是否选中
     */
    public JSONArray getMenus(List<Menu> menus, List<Integer> menuIds) {
        JSONArray array = new JSONArray();
        boolean checked;
        if (menus != null && !menus.isEmpty()) {
            for (Menu menu : menus) {
                checked = menuIds.contains(menu.getMenuId());
                array.add(putMenuInfo(menu,checked));
            }
        }
        return array;
    }

    /**
     * 菜单树节点信息
     */
    public JSONObject putMenuInfo(Menu menu, boolean checked) {
        JSONObject json = new JSONObject();
        json.put("id",menu.getMenuId());
        json.put("name",menu.getMenuName());
        json.put("pId",menu.getParentId());
        json.put("title",menu.getMenuName());
        json.put("checked",checked);
        return json;
    }

}
